package com.stream;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.junit.jupiter.api.Test;
import util.JacksonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StreamTest1 {
    @Getter
    @Setter
    @ToString
    class Teacher {
        private String name;
        private String gender;
        private int age;
        private List<Student> students = new ArrayList<>();
    }

    @Getter
    @Setter
    @ToString
    class Student {
        private String name;
        private String gender;
        private String address;
    }

    @Test
    void test() throws JsonProcessingException {
        List<Map<String, Object>> data = new ArrayList<>();
        data.add(Map.of("teacherName", "张三老师", "gender", "男", "age", 35, "studentName", "李四", "studentGender", "男", "address", "北京"));
        data.add(Map.of("teacherName", "张三老师", "gender", "男", "age", 35, "studentName", "王五", "studentGender", "男", "address", "上海"));
        data.add(Map.of("teacherName", "李老师", "gender", "女", "age", 30, "studentName", "赵六", "studentGender", "女", "address", "广州"));

        Map<String, Teacher> teacherMap = data.stream()
                .collect(Collectors.groupingBy(
                        item -> (String) item.get("teacherName"),
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> {
                                    Map<String, Object> itemMap = list.get(0);

                                    Teacher teacher = new Teacher();
                                    teacher.setName((String) itemMap.get("teacherName"));
                                    teacher.setGender((String) itemMap.get("gender"));
                                    teacher.setAge((int) itemMap.get("age"));
                                    for (Map<String, Object> studentData : list) {
                                        Student student = new Student();
                                        student.setName((String) studentData.get("studentName"));
                                        student.setGender((String) studentData.get("studentGender"));
                                        student.setAddress((String) studentData.get("address"));
                                        teacher.getStudents().add(student);
                                    }
                                    return teacher;
                                }
                        )
                ));

        var str = JacksonUtil.toFormatStr(teacherMap.values());
        System.out.println(str);
    }
}


